package com.wl.user.login.controller;

import com.wl.entity.Lvuser;
import com.wl.bean.Result;
import com.wl.biz.BizException;
import com.wl.user.login.DTO.UserUpdateDTO;
import com.wl.user.login.biz.ILvuserBiz;
import com.wl.user.login.biz.VerificationCodeBiz;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/lvuser")
public class lvuserController {

    @Autowired
    private ILvuserBiz lvuserBiz;

    @Autowired
    private VerificationCodeBiz verificationCodeBiz;

    JdbcTemplate jdbcTemplate;

    //注册
    @RequestMapping("/register")
    public Result register(@RequestBody Map<String, String> params, HttpServletRequest request){
        String head = params.get("head");
        String uname = params.get("uname");
        String zhanghao = params.get("zhanghao");
        String password = params.get("password");
        String email = params.get("email");
        String verificationCode = params.get("verificationCode");

        // 1. 验证验证码 - 使用Redis验证
        if (!verificationCodeBiz.verifyCode(email, verificationCode)) {
            return new Result(0, "验证码错误", null);
        }

        Lvuser user = lvuserBiz.findByEmail(email);
        Lvuser user1 = lvuserBiz.findByZhanghao(zhanghao);

        if(user == null && user1 == null){
            lvuserBiz.register(head,uname,zhanghao,password,email);
            return new Result(1,"注册成功",null);
        }else {
            return new Result(0,"账号或邮箱已存在，请重新输入",null);
        }
    }

    @RequestMapping("/login")
    public Result login(String head,String zhanghao, String password, String captcha, HttpServletRequest request) {
        // 调试日志
        System.out.println("尝试登录，账号：" + zhanghao + "，验证码：" + captcha);
        // 注意：实际生产环境中不应打印密码日志

        try {
            // 1. 验证验证码
            String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
            if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
                return new Result(0, "验证码错误", null);
            }

            // 2. 查询用户
            Lvuser user = lvuserBiz.findByZhanghao(zhanghao);
            System.out.println("查询结果：" + (user != null ? "用户存在" : "用户不存在"));

            if (user == null) {
                return new Result(0, "账号或密码错误", null);
            }

            // 3. 验证密码
            boolean loginSuccess = lvuserBiz.login(head,zhanghao, password);
            System.out.println("登录结果：" + loginSuccess);

            if (loginSuccess) {
                // 登录成功后清除验证码
                request.getSession().removeAttribute("captcha");

                // 可以将用户信息存入session
                request.getSession().setAttribute("currentUser", user);

                return new Result(1, "登录成功", user);
            } else {
                return new Result(0, "账号或密码错误", null);
            }
        } catch (Exception e) {
            System.err.println("登录异常：" + e.getMessage());
            e.printStackTrace();
            return new Result(0, "登录异常，请稍后再试", null);
        }
    }

    //用户所有信息查询
    @RequestMapping("/info")
    public Result getAllUsers(String zhanghao) {
        List<Lvuser> users = lvuserBiz.selectByZhanghao(zhanghao);
        if (!users.isEmpty()){
            return new Result(1,"查询成功",users.get(0));
        }
        return new Result(0,"用户不存在",null);
    }

    //用户信息修改
    @RequestMapping("/update")
    public Result updateUserInfo(UserUpdateDTO updateDTO){
        try {
            // 1. 参数基础校验
            if (updateDTO == null) {
                return new Result(400, "请求参数不能为空", null);
            }

            // 2. 必填字段校验
            if (updateDTO.getZhanghao() == null || updateDTO.getZhanghao().trim().isEmpty()) {
                return new Result(400, "账号不能为空", null);
            }
//
            if (updateDTO.getField() == null || updateDTO.getField().trim().isEmpty()) {
                return new Result(400, "字段类型不能为空", null);
            }

            // 4. 根据字段类型执行不同更新逻辑
            String field = updateDTO.getField();
            String value = updateDTO.getValue();

            switch (updateDTO.getField()) {
                case "head":
                    if (value == null || !value.matches("^img/\\w+\\.(png|jpg|jpeg)$")) {
                        return new Result(400, "头像路径格式不正确", null);
                    }
                    lvuserBiz.updateHead(updateDTO.getZhanghao(), updateDTO.getValue());
                    break;

                case "uname":
                    if (value == null || value.length() < 2 || value.length() > 20) {
                        return new Result(400, "用户名长度需在2-20个字符之间", null);
                    }
                    lvuserBiz.updateBasicInfo(
                            updateDTO.getZhanghao(),
                            updateDTO.getValue(),
                            null, null, null
                    );
                    break;

                case "gender":
                    try {
                        int gender = Integer.parseInt(value);
                        if (gender < 0 || gender > 2) {
                            return new Result(400, "性别参数不合法", null);
                        }
                        lvuserBiz.updateBasicInfo(
                                updateDTO.getZhanghao(),
                                null,
                                gender,
                                null, null
                        );
                    } catch (NumberFormatException e) {
                        return new Result(400,"性别参数必须为数字",null);
                    }
                    break;

                case "birthday":
                    if (!value.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
                        return new Result(400, "生日格式应为YYYY-MM-DD", null);
                    }
                    lvuserBiz.updateBasicInfo(
                            updateDTO.getZhanghao(),
                            null, null,
                            value,
                            null
                    );
                    break;

                case "bio":
                    if (value.length() > 200) {
                        return new Result(400, "个人简介不能超过200个字符", null);
                    }
                    lvuserBiz.updateBasicInfo(
                            updateDTO.getZhanghao(),
                            null, null, null,
                            value
                    );
                    break;

                case "email":
                    if (value == null || !value.matches("^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$")) {
                        return new Result(400, "邮箱格式不正确", null);
                    }
                    lvuserBiz.updateEmail(updateDTO.getZhanghao(), value);
                    break;

                case "password":
                    // 密码可以为空（比如用户想清空密码）
                    // 明确处理null值情况
                    String newPassword = (value == null) ? "" : value;
                    if (newPassword.length() > 0 && newPassword.length() < 6) {
                        return new Result(400, "密码长度不能少于6位", null);
                    }
                    lvuserBiz.updatePassword(updateDTO.getZhanghao(), newPassword);
                    break;

                default:
                    return new Result(400, "不支持字段修改", null);
            }

            return new Result(1, "更新成功", null);

        } catch (IllegalArgumentException e) {
            // 业务校验异常
            return new Result(400, e.getMessage(), null);
        } catch (Exception e) {
            System.err.println("用户信息更新失败：" + e.getMessage());
            e.printStackTrace(); // 打印堆栈信息
            return new Result(500, "系统繁忙，请稍后再试", null);
        }
    }

    @RequestMapping("/delete")
    public Result deleteZhanghao(@NotBlank(message = "账号不能为空")String zhanghao, @NotBlank(message = "密码不能为空")String password){
        try {
            int result = lvuserBiz.deleteZhanghao(zhanghao,password);

            if (result > 0){
                return new Result(1,"账号注销成功",null);
            }else {
                return new Result(0,"账号注销失败",null);
            }
        }catch (IllegalArgumentException e){
            //参数验证失败的异常
            return new Result(0,e.getMessage(),null); //返回具体参数错误
        } catch (RuntimeException e) {
            //业务逻辑异常(如密码错误)
            return new Result(0,e.getMessage(),null); //返回具体业务逻辑错误
        } catch (Exception e) {
            e.printStackTrace();
            //其他未知异常
            return new Result(0,"系统繁忙，请稍后再试",null);
        }
    }

    //批量获取用户
    @GetMapping("/batch-info")
    public Result batchUserInfo(@RequestParam("uids") String uids) {

        try {
            // 将逗号分隔的字符串转换为List<Integer>
            List<Integer> uidList = Arrays.stream(uids.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());

            // 调用服务层获取用户信息
            List<Lvuser> users = lvuserBiz.getBatchUserInfo(uidList);

            return new Result(1, "获取成功", users);
        } catch (Exception e) {
            return new Result(0, "获取用户信息失败: ",null);
        }
    }

    @RequestMapping("myinfo")
    Result myinfo(HttpSession session) throws BizException {
        Object myinfo = session.getAttribute("myinfo");
        if (myinfo == null) {
            throw new BizException("未登录");
        }
        return new Result(1,"已登录",myinfo);
    }

    @RequestMapping("logout")
    ModelAndView logout(ModelAndView modelAndView, HttpSession session){
        session.invalidate();
        modelAndView.setViewName("redirect:/");
        return modelAndView;
    }
}
